import cryptojs from '@/common/cryptojs.js'
let config = {
	plat_code: 12753,
	plat_status: 1, //1的时候是平台可用0的时候是平台关闭
	is_reg: 1, //0自动注册1手动注册
	baseUrl: '', //使用中的URL
	baseUrls: [], //存储的url数组
	socketUrls: [], //存储的socket数组
	getConfigRequest: async (progressCallback) => {
		// return Promise.resolve()
		await getConfigRequest(0, progressCallback)
	}
}
// Maximum retry attempts
const MAX_RETRIES = 3;
//获取配置
function getConfigRequest(attempt = 0, progressCallback) {
	return new Promise((resolve, reject) => {
		progressCallback && progressCallback('请求配置信息中...');
		// const url = 'https://zx-json-1328799719.cos.ap-seoul.myqcloud.com/123456.json?time=' + Math.random();
		const url = 'https://clab-json-1328391504.cos.accelerate.myqcloud.com/12753.json?time=' + Math.random();
		uni.request({
			url: url,
			method: 'GET',
			success: async (res) => {
				if (res.statusCode == 200) {
					if (res.data) {
						try {
							progressCallback && progressCallback('解析配置信息中...');
							let mydata = JSON.parse(cryptojs.DecryptAES(res.data))
							console.log('----', mydata);
							//如果是数组则筛选最快的连接，否则直接取
							if (Array.isArray(mydata.plat_download.api_url)) {
								progressCallback && progressCallback('正在选择节点...');
								mydata.baseUrl = await getFirstAvailableNode(mydata.plat_download
									.api_url);
								mydata.baseUrls = JSON.parse(JSON.stringify(mydata.plat_download
									.api_url))
							} else {
								mydata.baseUrl = mydata.plat_download.api_url;
								mydata.baseUrls = [mydata.plat_download.api_url]
							}

							//如果是数组取第一个
							if (Array.isArray(mydata.plat_download.ws_url)) {
								mydata.socketUrls = JSON.parse(JSON.stringify(mydata.plat_download
									.ws_url))
							} else {
								mydata.socketUrls = [mydata.plat_download.ws_url]
							}
							console.log('当前使用的URL:', mydata.baseUrl);
							progressCallback && progressCallback('节点选择完毕，更新配置信息...');
							config = Object.assign(config, mydata)

							//重新配置全局请求url
							uni.$u.http.setConfig((u_config) => {
								u_config.baseURL = config.baseUrl;
								return u_config
							})
							progressCallback && progressCallback('配置完成');
							resolve()
							return
						} catch (e) {}
					}
					reject('解析节点失败')
				} else {
					// 重试重试
					if (attempt < MAX_RETRIES) {
						progressCallback && progressCallback(`请求失败，重试中... 第 ${attempt + 1} 次`);
						console.warn(`Retrying... Attempt ${attempt + 1}`);
						setTimeout(() => {
							getConfigRequest(attempt + 1, progressCallback).then(resolve)
								.catch(reject);
						}, 1000);
					} else {
						reject('获取节点失败' + res.statusCode);
					}
				}
			},
			fail: (err) => {
				// 重试重试
				if (attempt < MAX_RETRIES) {
					progressCallback && progressCallback(`请求失败，重试中... 第 ${attempt + 1} 次`);
					console.warn(`Retrying... Attempt ${attempt + 1}`);
					setTimeout(() => {
						getConfigRequest(attempt + 1, progressCallback).then(resolve).catch(
							reject);
					}, 1000);
				} else {
					reject('获取节点失败');
				}
			}
		});
	})
}
// 如果缺少协议则添加协议的功能
function ensureProtocol(url) {
	if (/^(http:\/\/|https:\/\/)/i.test(url)) {
		return url;
	}
	return `http://${url}`;
}
// 选择最先响应的节点
async function getFirstAvailableNode(urls) {
	return new Promise((resolve, reject) => {
		let isResolved = false; // 标记是否已有请求成功
		let completedCount = 0; // 已完成请求的计数

		urls.forEach((url, index) => {
			testUrl(ensureProtocol(url))
				.then(result => {
					if (!isResolved) {
						isResolved = true; // 标记已有成功的请求
						resolve(result.url); // 返回第一个成功的 URL
					}
				})
				.catch(() => {
					// 计数增加
					completedCount++;
					if (!isResolved && completedCount === urls.length) {
						// 如果所有请求都完成了且没有成功，则返回默认值
						resolve(ensureProtocol(urls[0]));
					}
				});
		});
	});
}
// 测试 URL 响应时间
function testUrl(url) {
	return new Promise((resolve, reject) => {
		const startTime = Date.now();
		uni.request({
			url: url + '/ping?time=' + Math.random(), // 添加随机参数防止缓存
			method: 'HEAD',
			success: (e) => {
				const endTime = Date.now();
				console.log('12313131----', endTime - startTime, 'url', url);
				resolve({
					url,
					time: endTime - startTime
				});
			},
			fail: (e) => {
				const endTime = Date.now();
				console.log('12313131bai----', endTime - startTime, '--', e);
				reject({
					url,
					time: Infinity
				}); // 如果失败则设置为最大时间
			}
		});
	});
}
export default config